package com.itsu.spbspider.controller.handler;

import com.itsu.spbspider.exception.ApiException;
import com.itsu.spbspider.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author suben
 * @create time 2020/2/7 23:17
 */
@ControllerAdvice
@Slf4j
public class ExceptionControllerHandler {


    @ExceptionHandler(value = Exception.class)
    public Object handler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        log.error("unexpected exception happened", e);
        String content = request.getHeader("X-Requested-With");
        String app = request.getHeader("app");
        if ((StringUtils.isNotBlank(content) && "XMLHttpRequest".equals(content)) || (StringUtils.isNotBlank(app) && "app-req".equals(app))) {
            Map map = new HashMap();
            map.put("code", 500);
            map.put("msg", "未知错误");
            return map;
        } else {
            ModelAndView mav = new ModelAndView("/error/500");
            mav.addObject("code", 500);
            mav.addObject("msg", "未知错误");
            return mav;
        }
    }

    @ExceptionHandler(value = SystemException.class)
    public Object handlerSys(HttpServletRequest request, HttpServletResponse response, Exception e) {
        if (e instanceof ApiException) {
            return handlerApi(request, response, e);
        }
        log.error("system exception happened", e);
        String content = request.getHeader("X-Requested-With");
        if (StringUtils.isNotBlank(content) && "XMLHttpRequest".equals(content)) {
            Map map = new HashMap();
            map.put("code", 501);
            map.put("msg", e.getMessage());
            return map;
        } else {
            ModelAndView mav = new ModelAndView("/error/500");
            mav.addObject("code", 501);
            mav.addObject("msg", e.getMessage());
            return mav;
        }
    }

    @ExceptionHandler(value = ApiException.class)
    @ResponseBody
    public Map handlerApi(HttpServletRequest request, HttpServletResponse response, Exception e) {
        log.error("API exception happened", e);
        ApiException ex = (ApiException) e;
        Map map = new HashMap();
        map.put("code", ex.getCode());
        map.put("msg", ex.getMessage());
        return map;
    }
}
